package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.Account;
import dao.AccountDAO;

/**
 * Servlet implementation class Login
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String err = "<span>Đăng nhập không thành công: ";
		if (request.getParameter("j_username").equals("")
				|| request.getParameter("j_password").equals("")) {
			err += "vui lòng điền đầy đủ thông tin tên tài khoản và mật khẩu</span>";
			request.setAttribute("err", err);
			request.getRequestDispatcher("login").forward(request, response);
		} else {
			// check database
			Account acc = AccountDAO.selectByUsername(request
					.getParameter("j_username"));
			String passInput = request.getParameter("j_password");
			if (acc != null
					&& AccountDAO.selectPass(acc.getId()).equals(passInput)) {
				HttpSession session = request.getSession();
				session.setAttribute("account", acc);

				Cookie username = new Cookie("username", acc.getUsername());
				username.setMaxAge(24 * 60 * 60);
				Cookie pass = new Cookie("pass",
						request.getParameter("j_password"));
				pass.setMaxAge(24 * 60 * 60);

				// test
				// request.getCookies();

				response.addCookie(username);
				response.addCookie(pass);

				response.sendRedirect("forum");
			} else {
				err += "tên tài khoản hoặc mật khẩu không chính xác</span>";
				request.setAttribute("err", err);
				request.getRequestDispatcher("login")
						.forward(request, response);
			}
		}
	}
}
